<script setup>
import { format } from 'date-fns';
import dayjs from 'dayjs';
const urlHome = useUrl();
const username = useCookie('username');
const selectedContr = ref('open')
const isOpen = ref(false)
const organizationName = ref('')
const contractNumber = ref('')
const startDate = ref(new Date())
const endDate = ref(new Date())
const productError = ref('')
// const selectedDate = ref({ start: sub(new Date(), { days: 14 }), end: new Date() })
const options = [{
	value: 'open',
	label: 'Действующие',
	icon: 'i-heroicons-document-check'
}, {
	value: 'close',
	label: 'Расторгнутые',
	icon: 'i-heroicons-x-mark'
}, {
	value: 'expired',
	label: 'Просроченные',
	icon: 'i-heroicons-calendar-days'
}]

const { data: contractList, execute: refreshContractList } = await useFetch(`${urlHome.value}orders/get_contract/`);

const contractListFiltered = computed(() => selectedContr.value === 'open' ? contractList.value.filter(obj => obj.is_closed === false && obj.is_active === true) : selectedContr.value === 'close' ? contractList.value.filter(obj => obj.is_closed === true) : contractList.value.filter(obj => obj.is_active === false))

async function addContract() {
	const response = await $fetch(`${urlHome.value}orders/contract_add/`, {
		method: 'POST',
		body: {
			organization_name: organizationName.value,
			contract_number: contractNumber.value,
			date_start: dayjs(startDate.value).format('YYYY-MM-DD'),
			date_end: dayjs(endDate.value).format('YYYY-MM-DD'),
			username: username.value
		}
	})
	if (response) {
		console.log("addContract")
		isOpen.value = false
		refreshContractList()
		organizationName.value = ''
		contractNumber.value = ''
		startDate.value = new Date()
		endDate.value = new Date()
	}
}

async function deleteContract(id) {
	const response = await $fetch(`${urlHome.value}orders/delete_contract/`, {
		method: 'DELETE',
		body: {
			contract_id: id,
			username: username.value
		}
	})
	if (response) {
		console.log("deleteContract")
		refreshContractList()
	}
}
</script>
<template>
	<div class="pl-2">
		<div>
			<UButton label="Добавить договор" @click="isOpen = true" />
		</div>
		<div class="pt-2" v-auto-animate>
			<div class="flex flex-row gap-6">
				<div>
					<URadioGroup v-model="selectedContr" legend="Фильтр договоров:" :options="options">
						<template #label="{ option }">
							<p class="italic text-xl">
								<UIcon :name="option.icon" />
								{{ option.label }}
							</p>
						</template>
					</URadioGroup>
				</div>
			</div>
			<div v-for="value in contractListFiltered" :key="value.id" :class="value.is_closed || !value.is_active ?
				`flex flex-row text-xl gap-4 border border-blue-400 font-bold bg-red-200` :
				`flex flex-row text-xl gap-4 border border-blue-400 font-bold bg-green-200`"
				class="flex flex-row text-xl gap-4 border border-blue-400 font-bold bg-green-200">
				<div>
					<UButton icon="i-heroicons-trash" color="red" label="Удалить" @click="deleteContract(value.id)" />
				</div>
				<div>{{ value.organization_name }}</div>
				<div>{{ value.contract_number }}</div>
				<div>Действует с: {{ dayjs(value.start_date).format('DD.MM.YYYY') }}</div>
				<div>по: {{ dayjs(value.end_date).format('DD.MM.YYYY') }} </div>
				<div :class="value.is_closed ? 'text-red-800' : 'text-green-800'">{{ value.is_closed ? `Расторгнут` :
					`Действующий
					договор` }}
				</div>
			</div>
		</div>
		<UModal v-model="isOpen">
			<UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
				<template #header>
					<div class="flex items-center justify-between">
						<h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
							Добавить договор
						</h3>
						<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
							@click="isOpen = false" />
					</div>
				</template>

				<div>
					<div>
						<label>Название организации:</label>
						<UInput v-model="organizationName" />
						{{ organizationName }}
					</div>
					<div>
						<label>Номер договора:</label>
						<UInput v-model="contractNumber" />
						{{ contractNumber }}
					</div>
					<div class="flex flex-row justify-between">
						<div>
							<label>Дата начала:</label>
							<UPopover :popper="{ placement: 'bottom-start' }">
								<UButton icon="i-heroicons-calendar-days-20-solid"
									:label="format(startDate, 'd.MM.yyy')" />

								<template #panel="{ close }">
									<DatePicker v-model="startDate" is-required @close="close" />
								</template>
							</UPopover>
						</div>
						<div>
							<label>Дата окончания:</label>
							<UPopover :popper="{ placement: 'bottom-start' }">
								<UButton icon="i-heroicons-calendar-days-20-solid"
									:label="format(endDate, 'd.MM.yyy')" />

								<template #panel="{ close }">
									<DatePicker v-model="endDate" is-required @close="close" />
								</template>
							</UPopover>
						</div>
					</div>
					<div class="text-red-600 font-bold">{{ productError }}</div>
					<div class="py-2">
						<UButton label="Добавить" @click="addContract" />
					</div>
					<!-- organization_name = models.TextField(max_length=500, verbose_name="Организация")
					contract_number = models.CharField(max_length=100, verbose_name="Номер договора")
					start_date = models.DateField(verbose_name="Дата начала договора")
					end_date = models.DateField(verbose_name="Дата окончания договора") -->
				</div>
			</UCard>
		</UModal>
	</div>
</template>